package LinkedList;

public class LinkedList<E> {
    Node<E> head = new Node<E>(null);
    int size;

    static class Node<E> {
        E e;
        Node<E> next;

        public Node(E e) {
            this.e = e;
            this.next = null;
        }
    }

    public void add(E e) {
        if (head == null) {
            head = new Node<>(e);
            return;
        }
        Node<E> curr = head;
        while (curr.next != null) {
            curr = curr.next;
        }
        curr.next = new Node<E>(e);
        size++;
    }

    public void add2(E e, int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("非法");
        }
        Node<E> curr = head;
        for (int i = 0; i < index; i++) {
            curr = curr.next;
        }
        Node<E> node = new Node<E>(e);
        node.next = curr.next;
        curr.next = node;
        size++;

    }

    public void print() {
        Node<E> curr = head;
        while (curr != null) {
            System.out.println(curr.e + " ");
            curr = curr.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        LinkedList<Integer> list = new LinkedList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add2(5,1);
        list.print();
    }
}

